import { login, getinfo } from '@/api/user'

import { getToken, setToken, removeToken } from '@/utils/auth'
import router from '@/router'
import { baiduToken, removeBaiduToken } from '@/api/baid'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
    // 头像 可以先写死
    avatar: 'https://k.sinaimg.cn/n/sinakd20117/0/w800h800/20240127/889b-4c8a7876ebe98e4d619cdaf43fceea7c.jpg/w700d1q75cms.jpg'
  }
}

const state = getDefaultState()

const mutations = {
  // 设置登录token
  setToken(state, token) {
    state.token = token;
    setToken(token);
  },

  // 设置用户基本信息
  setUserInfo(state, userInfo) {
    state.userInfo = { ...userInfo }
  },

  // 删除cookie
  removeToken(state) {
    state.token = null;
    removeToken();
  },

  // 删除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // user login
  async login(context, data) {
    const res = await login(data);
    console.log("登录状态：" + res);
    context.commit('setToken', res.token)
  },

  // 获取用户的基本资料
  async getinfo(context) {
    const res = await getinfo();
    console.log(res);
    context.commit('setUserInfo', res)
    return res
  },

  // 退出登录
  logout(context) {
    // 删除toekn 相当于手动删除了cookie
    context.commit('removeToken')
    // 删除用户资料
    context.commit('removeUserInfo')
    //  跳转到登录页面
    router.push('/login')
  },


  // 授权token
  async baiduToken(context, token) {
    const row = await baiduToken(token);
    if (row) {
      const res = await getinfo();
      context.commit('setUserInfo', res);
      router.push('/example/authorization')
      return res;
    }
  },

  // 移除授权
  async removeBaiduTokens(context) {
    await removeBaiduToken();
    const res = await getinfo();
    context.commit('setUserInfo', res)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

